package com.byb.server.repository;

import com.byb.server.domain.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;

import java.util.Collection;
import java.util.List;

/**
 * Spring Data JPA repository for the Product entity.
 */
@SuppressWarnings("unused")
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    @Query("select distinct product from Product product left join fetch product.wordKeys")
    List<Product> findAllWithEagerRelationships();

    @Query("select product from Product product left join fetch product.wordKeys where product.id =:id")
    Product findOneWithEagerRelationships(@Param("id") Long id);

    @Query(value = "SELECT p.* FROM product p JOIN product_word_key pk ON pk.products_id = p.id JOIN word_key w ON w.id = pk.word_keys_id WHERE w.id IN ( ?1 ) GROUP BY p.id HAVING COUNT(DISTINCT w.key_name) = ?2 \n#pageable\n", nativeQuery = true)
     Page<Product> findAllByWordKeysIsIn(Collection<Long> query, int num,Pageable pageable);

    @Query(value = "SELECT p.* FROM product p JOIN product_word_key pk ON pk.products_id = p.id JOIN word_key w ON w.id = pk.word_keys_id WHERE w.id IN ( ?1 ) GROUP BY p.id HAVING COUNT(DISTINCT w.key_name) = ?2", nativeQuery = true)
    List<Product> findAllByWordKeysIsInNoPage(Collection<Long> query, int num);
}
